package com.everydayflash.cart.math {
	import com.everydayflash.cart.core.AbstractSketch;
	import com.everydayflash.cart.core.Pixel3D;
	
	import flash.geom.Matrix3D;
	import flash.geom.PerspectiveProjection;
	import flash.geom.Vector3D;		

	/**
	 * @author bartekd
	 */
	public class Geom1 extends AbstractSketch {

		private var pts:Vector.<Pixel3D>;
		private var projection:Matrix3D;
		private var angleX:Number = 0;
		private var angleY:Number = 0;
		private var matrix:Matrix3D;

		override protected function init():void {
			var p:PerspectiveProjection = new PerspectiveProjection();
			p.focalLength = 400;
			//			p.projectionCenter = new Point(stage.stageWidth / 2, stage.stageHeight / 2);
			projection = p.toMatrix3D();
			matrix = new Matrix3D();
			pts = new Vector.<Pixel3D>();
			
			var a:Pixel3D = new Pixel3D(50,50,0,0,0xffffff);			var b:Pixel3D = new Pixel3D(70,10,20,0,0xffffff);
			
			var cv:Vector3D = a.crossProduct(b);
			cv.normalize();
			cv.scaleBy(-100);
			var c:Pixel3D = new Pixel3D(cv.x, cv.y, cv.z, cv.w, 0x808080);
			
			pts.push(
				new Pixel3D(100, 0, 0, 0, 0x0000ff), 
				new Pixel3D(0, 100, 0, 0, 0x00ff00), 
				new Pixel3D(0, 0, 100, 0, 0xff0000),
				a, b, c);
		}

		override protected function draw():void {
			canvas.graphics.clear();
			clearBCanvas();

			angleX -= (mouseX - sw / 2) / sw / 2 * 10;
			angleY += (mouseY - sh / 2) / sh / 2 * 10;

			matrix.identity();
			matrix.appendRotation(angleX, new Vector3D(0, 0, 1));
			matrix.appendRotation(angleY, new Vector3D(1, 0, 0));
			matrix.appendTranslation(0, 0, 350);

			for (var i:int = 0;i < pts.length; i++) {
				var iv:Pixel3D = pts[i];
				
				var pv:Vector3D = matrix.transformVector(iv);
				pv = projection.transformVector(pv);
				
//				iv.update(matrix.transformVector(iv));
//				iv.update(projection.transformVector(iv));

				pv.project();
				canvas.graphics.lineStyle(1, iv.color, 1);
				canvas.graphics.moveTo(sw / 2, sh / 2);
				canvas.graphics.lineTo(sw / 2 + pv.x, sh / 2 + pv.y);
			}
			
			bcanvas.draw(canvas);
//			bcanvas.applyFilter(bcanvas, bcanvas.rect, new Point(), new BlurFilter(8,8,1));
//			bcanvas.colorTransform(bcanvas.rect, new ColorTransform(1,1,1,.8));
		}
	}
}
